#!/usr/local/bin/python2.6
import os
import sys
import MySQLdb
import string
import time
import cloudapi


def isDigtal(myNum):
    nums = string.digits
    if type(myNum) is not str:
        return False
    else:
        for temp in myNum:
            if temp not in nums:
                return False
        return True
        
def checkParameter(conn):
    global mtid
    global stid
    global sncnt
    
    if not conn:
        print "Can not connect to database, Fail!"
        return -1
    paraCnt=len(sys.argv)
    if paraCnt != 3:
        return 0
    para=sys.argv[1]
    if para != "-mpi":
        return 0
    para = sys.argv[2]
    master_type,salve_type,salve_cnt=para.split(',')
    mtname,mtid=master_type.split('=')
    stname,stid=salve_type.split('=')
    snname,sncnt=salve_cnt.split('=')
    
    if mtname != "mtype" or stname != "stype" or snname != "snum":  
        return 0
    if not isDigtal(mtid):
        return 0
    if not isDigtal(stid):
        return 0
    if not isDigtal(sncnt):
        return 0
    flag = conn.execute("select vm_id from vm_info where vm_id = " + mtid);
    if flag == 0:
        print "No Master Node VM ", mtid 
        return 0
    flag = conn.execute("select vm_id from vm_info where vm_id = " + stid);
    if flag == 0:
        print "No Salve Node VM ", stid
        return 0
    sncnt=int(sncnt)
    return 1

def connectDB():
    connect=MySQLdb.connect(host="localhost",port=3306,user="cloud",passwd="cloudpass",db="cloud")
    return connect

def cursorDB(connect):        
    conn=connect.cursor()
    return conn

def closeConnect(connect):
    connect.close()

def closeCursor(cursor):
    cursor.close()


mtid="0"
stid="0"
sncnt="0"
str_command="command format:\n" + \
"   cjob -mpi mtype=master_type_ID,stype=salve_type_ID,snum=salve_number\n" + \
"   For example: cjob -mpi mtype=1,stype=2,snum=2"

def getVmForMpi(mtid,stid,sncnt):
    
    connect=connectDB()
    conn=cursorDB(connect)
    conn.execute("select mem,cpu,img_store_path from vm_info where vm_id = "+mtid)
    rows=conn.fetchall()
    m_mem=int(rows[0][0])
    m_vcpu=int(rows[0][1])
    m_img_path=rows[0][2]

    conn.execute("select mem,cpu,img_store_path from vm_info where vm_id = "+stid)
    rows=conn.fetchall()
    s_mem=int(rows[0][0])
    s_vcpu=int(rows[0][1])
    s_img_path=rows[0][2]
    closeCursor(conn)
    closeConnect(connect)

    #import cloudapi
    #HVM={ 'memory':'512','vcpu':'2','img':'/srv/cloud/images/rhel5_x86_64_base.img','count':2 }
    #ret=cloudapi.create_vm(HVM)
    HVM_MASTER={ 'memory':str(m_mem),'vcpu':str(m_vcpu),'img':m_img_path,'count':1 }
    HVM_SALVE={ 'memory':str(s_mem),'vcpu':str(s_vcpu),'img':s_img_path,'count':sncnt }   
    print HVM_MASTER
    print HVM_SALVE
    ret_m=cloudapi.create_vm(HVM_MASTER)
    ret_s=cloudapi.create_vm(HVM_SALVE)
    #ret_m=[['29', '192.168.100.129']]
    #ret_s=[['30', '192.168.100.130'], ['31', '192.168.100.131']] 
    print "yes"
    print ret_m 
    print ret_s 
    connect=connectDB()
    conn=cursorDB(connect)
    tmp=str(time.time()).split('.')
    startTime=str(tmp[0])
    conn.execute("insert into mpi_env(user,status,start_time,end_time) values('root','running',"+startTime+",0)")
    conn.execute("select max(env_id) from mpi_env")    
    rows=conn.fetchall()
    env_id=rows[0][0]
    
    conn.execute("insert into env_resource(env_id,vm_id,vm_ip,vm_type) values("+str(env_id)+","+str(ret_m[0][0])+",'" +str(ret_m[0][1])+"','master')")
    
    for tmp in ret_s:
        conn.execute("insert into env_resource(env_id,vm_id,vm_ip,vm_type) values("+str(env_id)+","+str(tmp[0])+",'" +str(tmp[1])+"','salve')")

    closeCursor(conn)
    closeConnect(conn)
    print "Job ID ", env_id    
    
if __name__ == "__main__":
    
    connect=connectDB()
    conn=cursorDB(connect)
    flag = checkParameter(conn)
    closeCursor(conn)
    closeConnect(connect)
    if flag == -1:
        sys.exit(0)
    if flag == 0:
        print str_command
        sys.exit(0)
    getVmForMpi(mtid,stid,sncnt)


